package config

import (
	"encoding/json"
	"io/ioutil"
)

type Config struct {
	Client  client   `json:"client"`
	Server  server   `json:"server"`
	Actions []action `json:"actions"`
}

func New() *Config {
	return &Config{}
}

func (c *Config) Load(jsonPath string) error {
	data, err := ioutil.ReadFile(jsonPath)
	if err != nil {
		return err
	}
	return c.Modify(data)
}

func (c *Config) Save(jsonPath string) error {
	err, data := c.Dump()
	if err != nil {
		return err
	}
	err = ioutil.WriteFile(jsonPath, data, 0644)
	if err != nil {
		return err
	}
	return nil
}

func (c *Config) Dump() (error, []byte) {
	data, err := json.Marshal(c)
	if err != nil {
		return err, nil
	}
	return nil, data
}

func (c *Config) Modify(data []byte) error {
	err := json.Unmarshal(data, c)
	if err != nil {
		return err
	}
	return nil
}
